package com.lx.controller;

import com.lx.config.WxPayConfig;
import com.lx.entity.Order;
import com.lx.service.OrderService;
import com.lx.util.Result;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 2025/9/21 12:54
 * author: 向远洋
 */
@RequestMapping("/api")
@RestController // 改为@RestController，因为返回的是JSON数据
public class WxPayController {
    @Autowired
    OrderService orderService;
    private static Logger logger = LoggerFactory.getLogger(WxPayController.class);
    private final WxPayConfig wxPayConfig;
    private final NativePayService nativePayService;

    // 通过构造函数注入依赖
    public WxPayController(WxPayConfig wxPayConfig) {
        this.wxPayConfig = wxPayConfig;
        this.nativePayService = new NativePayService.Builder()
                .config(wxPayConfig.getConfig())
                .build();
    }

    @PostMapping("/wx/zf")
    public Result zf(@RequestBody Order order) {
        PrepayRequest request = new PrepayRequest();

        Amount amount = new Amount();
        amount.setTotal(1); // 这里应该使用订单的实际金额 order.getAmount()
        request.setAmount(amount);

        // 使用注入的wxPayConfig获取配置
        request.setAppid(wxPayConfig.getAppid());
        request.setMchid(wxPayConfig.getMerchantId());
        request.setDescription("易买网购物车商品");
        request.setNotifyUrl(wxPayConfig.getNotifyUrl());
        request.setOutTradeNo(order.getSerialNumber());

        PrepayResponse response = nativePayService.prepay(request);
        return Result.success().add("pay_url", response.getCodeUrl());
    }

    @PostMapping("/wxNotify")
    public void wxNotify(@RequestHeader(value = "Wechatpay-Signature") String signature,
                         @RequestHeader(value = "Wechatpay-Serial") String serialNumber,
                         @RequestHeader(value = "Wechatpay-Timestamp") String timestamp,
                         @RequestHeader(value = "Wechatpay-Nonce") String nonce,
                         @RequestHeader(value = "Wechatpay-Signature-Type") String signatrueType,
                         @RequestBody String body,
                         HttpServletResponse response) {

        NotificationParser notificationParser = new NotificationParser(wxPayConfig.getConfig());
        RequestParam requestParam = new RequestParam.Builder()
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .serialNumber(serialNumber)
                .signType(signatrueType)
                .body(body).build();

        try {
            Transaction transaction = notificationParser.parse(requestParam, Transaction.class);

            if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
                logger.info("支付成功 - 商户订单号[{}], 微信交易号[{}]",
                        transaction.getOutTradeNo(), transaction.getTransactionId());
                // 这里应该调用你的订单服务更新订单状态
                System.out.println(orderService.modifyOrderStatusBySerialNumber(transaction.getOutTradeNo(), 1) ? "付款完成！" : "数据库修改订单失败");
            }
            response.setStatus(200);

        } catch (ValidationException e) {
            logger.error("验证签名错误！", e);
            response.setStatus(500);
        }
    }
}